<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-06-06 17:22:55
 * @LastEditors: 976901273@qq.com
 * @LastEditTime: 2023-11-20 14:23:36
 * @Description:
 *
-->

<template>
  <el-dialog
    class="add-intelligent-rule-dialog"
    :title="!isEdit ? '添加告警规则' : '编辑告警规则'"
    :visible="show"
    width="40vw"
    top="7vh"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeClick"
  >
    <div class="steps">
      <div class="order">1</div>
      <div class="line"></div>
      <div class="order">2</div>
      <div class="line line2" :style="{ height: form.resType !== '所有微服务' ? '228px' : '207px' }"></div>
      <div class="order">3</div>
      <div class="line line3"></div>
      <div class="order">4</div>
      <div class="line line4"></div>
      <div class="order">5</div>
    </div>
    <el-form
      ref="addForm"
      class="add-form"
      size="medium"
      :rules="rules"
      :model="form"
      label-width="auto"
    >
    <div class="title">告警名称</div>
      <el-form-item label="告警名称" prop="ruleName">
        <el-input
          v-model="form.ruleName"
          :disabled="isEdit"
          placeholder="请输入告警名称"
        />
      </el-form-item>
      <el-form-item label="告警类型" prop="ruleType">
        <el-radio-group v-model="form.ruleType" @change="changeRuleTpye"  :disabled="isEdit" size="small">
          <el-radio-button label="智能规则"></el-radio-button>
          <el-radio-button label="普通规则"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <div class="title">指定资源</div>
      <el-form-item label="选择集群" prop="clusterName">
        <el-select
          v-model="form.clusterName"
          placeholder="请选择集群"
          style="width: 100%"
          :loading="clusterOptionsLoading"
          :disabled="isEdit"
          @change="clusterNameChange"
        >
          <el-option
            v-for="(item, index) in clusterOptions"
            :key="index"
            :label="item.k8sClusterName"
            :value="item.k8sClusterName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资源类型" prop="resType">
        <el-select
          v-model="form.resType"
          placeholder="请选择资源类型"
          style="width: 100%"
          :disabled="isEdit"
          @change="resTypeChange"
        >
          <el-option
            v-for="item in resTypeOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.resType !== '所有微服务'"
        label="资源名称"
        prop="resInfo"
      >
        <el-select
          v-model="form.resInfo"
          placeholder="请选择资源名称"
          style="width: 100%"
          :loading="resInfoOptionsLoading"
          no-data-text="请先选择合适的集群"
          :disabled="isEdit"
          @change="resInfoChange"
        >
          <el-option
            v-for="item in resInfoOptions"
            :key="item.microSvcId"
            :label="item.microServiceName"
            :value="item.microServiceName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="指标名称" prop="indicatorName">
        <el-select
          v-if="form.ruleType=='智能规则'&&this.arch=='CPU'"
          v-model="form.indicatorName"
          @change="changeIndicatorName"
          placeholder="请选择指标名称"
          style="width: 100%"
          :disabled="isEdit"
        >
          <el-option
            v-for="item in indicatorNameOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
        <el-select
          v-if="form.ruleType=='智能规则'&&this.arch=='GPU'"
          v-model="form.indicatorName"
          @change="changeIndicatorName"
          placeholder="请选择指标名称"
          style="width: 100%"
          :disabled="isEdit"
        >
          <el-option
            v-for="item in indicatorNameOptions2"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
        <el-select
          v-if="form.ruleType=='普通规则'&&this.arch=='CPU'"
          v-model="form.indicatorName"
          @change="changeIndicatorName"
          placeholder="请选择指标名称"
          style="width: 100%"
          :disabled="isEdit"
        >
          <el-option
            v-for="item in indicatorNameOptions3"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
        <el-select
          v-if="form.ruleType=='普通规则'&&this.arch=='GPU'"
          v-model="form.indicatorName"
          @change="changeIndicatorName"
          placeholder="请选择指标名称"
          style="width: 100%"
          :disabled="isEdit"
        >
          <el-option
            v-for="item in indicatorNameOptions4"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <div class="title">告警规则</div>
      <div class="threshold-wrapper">
        <div class="subtitle" v-show="form.ruleType=='智能规则'">智能阈值设定</div>
        <div style="position:relative"  v-if="form.ruleType=='普通规则'">
          <div class="subtitle">历史监控数据</div>
          <el-select v-model="form.ruleExp.duration" placeholder="请选择" style="top: 0px;width: 120px;position: absolute;left: 100px;" size="mini">
            <el-option
              v-for="item in historyMonitorOptions1"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-select v-model="form.ruleExp.type" placeholder="请选择" style="top: 0px;width: 100px;position: absolute;left: 240px;" size="mini">
            <el-option
              v-for="item in historyMonitorOptions2"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-select v-model="form.ruleExp.symbol" placeholder="请选择" style="top: 0px;width: 100px;position: absolute;left: 360px;" size="mini">
            <el-option
              v-for="item in historyMonitorOptions3"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-input v-model="form.ruleExp.threshold" placeholder="请输入内容" style="top: 0px;width: 100px;position: absolute;left: 480px;" size="mini"></el-input>
          <div style="top: 3px;width: 100px;position: absolute;left: 600px;font-weight:600">单位&nbsp;&nbsp;{{unit}}</div>
        </div>
        <div id="threshold-chart"></div>
      </div>
      <div class="title">告警级别</div>
      <el-form-item label="告警级别" prop="alarmLevel">
        <el-radio-group v-model="form.alarmLevel">
          <el-radio
            v-for="item in levelOptions"
            :key="item.value"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="title">触发条件</div>
      <el-form-item label="冷却时间" prop="coolTime">
        <el-select v-model="form.coolTime" placeholder="请选择">
          <el-option
            v-for="item in coolTimeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancelClick">取 消</el-button>
      <el-button
        type="primary"
        size="small"
        :loading="confirmLoading"
        @click="confirmClick"
      >确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as echarts from 'echarts'
import {
  addIntelligentRule,
  updateIntelligentRule,
  addRule,
  updateRule
} from '@/api/cnap/statis-analysis'
import {
  getAllClusterName,
  getAllMicroSvcName,
  getAlarmSvcInfo,
  getIntelligentAlarmThreshold
} from '@/api/cnap/self-intelligence-ops'
import { ALARM_LEVEL } from '@/utils/cnap/constant'
import { parseTime } from '@/utils/utils'

export default {
  name: 'AddIntelligentDialog',
  components: {},
  props: {
    // 是否显示
    show: {
      type: Boolean,
      default: false
    },
    // 是否编辑
    isEdit: {
      type: Boolean,
      default: false
    },
    // 应用信息
    info: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      unit:'',
      arch:'CPU',
      clusterOptions: [], // 集群选项
      resTypeOptions: ['微服务', '所有微服务'], // 资源类型选项
      resInfoOptions: [], // 资源名称选项
      historyMonitorOptions1:[
        {
          value: '1',
          label: '连续1分钟'
        }, {
          value: '2',
          label: '连续2分钟'
        }, {
          value: '3',
          label: '连续3分钟'
        }, {
          value: '5',
          label: '连续5分钟'
        }, {
          value: '10',
          label: '连续10分钟'
        }, {
          value: '15',
          label: '连续15分钟'
        }, {
          value: '30',
          label: '连续30分钟'
        }, {
          value: '45',
          label: '连续45分钟'
        }
        , {
          value: '60',
          label: '连续60分钟'
        }
      ],//历史监控数据第一个选择框
      historyMonitorOptions2:[
        {
          value: '平均值',
          label: '平均值'
        }, {
          value: '最大值',
          label: '最大值'
        }, {
          value: '最小值',
          label: '最小值'
        }
      ],//历史监控数据第2个选择框
      historyMonitorOptions3:[
        {
          value: '>',
          label: '>'
        }, {
          value: '>=',
          label: '>='
        }, {
          value: '=',
          label: '='
        }
        , {
          value: '<',
          label: '<'
        }
        , {
          value: '<=',
          label: '<='
        }
      ],//历史监控数据第3个选择框
      coolTimeOptions:[
        {
          value: '5',
          label: '5分钟'
        }, {
          value: '15',
          label: '15分钟'
        }, {
          value: '30',
          label: '30分钟'
        }, {
          value: '60',
          label: '60分钟'
        }, {
          value: '180',
          label: '3小时'
        }, {
          value: '360',
          label: '6小时'
        }, {
          value: '720',
          label: '12小时'
        }, {
          value: '1440',
          label: '24小时'
        }
      ],//冷却时间选项
      indicatorNameOptions: ['CPU使用率', '请求响应时间'], // 指标名称选项
      indicatorNameOptions2: ['CPU使用率', '请求响应时间','显卡温度'], // 指标名称选项
      indicatorNameOptions3: ['CPU使用率', '内存使用率','磁盘IOPS','磁盘吞吐量'], // 指标名称选项
      indicatorNameOptions4: ['CPU使用率', '内存使用率','显存使用率','GPU使用率','显卡温度'], // 指标名称选项
      levelOptions: ALARM_LEVEL, // 级别选项
      clusterOptionsLoading: false,
      resInfoOptionsLoading: false,
      resInfos: [], // 用户选择的资源 所有微服务时是多个
      form: {
        ruleName: '', // 告警名称
        ruleType:'智能规则',//告警类型
        duration: 5, // 持续时间
        clusterName: '', // 集群
        resType: '', // 资源类型
        resInfo: '', // 资源名称
        indicatorName: '', // 指标名称
        threshold: 0, // 阈值
        alarmLevel: '', // 告警级别
        coolTime:'',//冷却时间
        ruleExp:{
          duration:'5',
          type:'平均值',
          symbol:'=',
          threshold:'0',
        }
      }, // 表单
      // 校验规则
      rules: {
        // 集群
        clusterName: [{ required: true, message: '请选择集群' }],
        // 资源类型
        resType: [{ required: true, message: '请选择资源类型' }],
        // 资源名称
        resInfo: [{ required: true, message: '请选择资源名称' }],
        // 告警名称
        ruleName: [
          { required: true, message: '请输入告警名称', trigger: 'blur' }
        ],
        // 指标名称
        indicatorName: [{ required: true, message: '请选择指标名称' }],
        // 告警级别
        alarmLevel: [
          { required: true, message: '请选择告警级别', trigger: 'blur' }
        ],
        coolTime: [
          { required: true, message: '请选择冷却时间', trigger: 'blur' }
        ]
      },
      confirmLoading: false,
      chart: null // 图表
    }
  },
  computed: {
    /**
     * @description: 图表数据监听相关参数
     * @return {*}
     */
    chartWatchParam() {
      return {
        resInfos: this.resInfos,
        indicatorName: this.form.indicatorName
      }
    },
    /**
     * @description: CPU使用率图表
     * @return {*}
     */
    isCPUChart() {
      return this.form.indicatorName === 'CPU使用率'
    }
  },
  watch: {
    /**
     * @description: 监听是否编辑
     * @return {*}
     */
    isEdit: {
      handler(newVal) {
        if (newVal) {
          // 初始化数据
          this.form.ruleType = this.info.ruleType
          this.form.alarmLevel = this.info.alarmLevel
          this.form.ruleName = this.info.ruleName
          this.form.duration = this.info.duration
          this.form.clusterName = this.info.resourceInfo.clusterName
          this.form.resType = this.info.resourceInfo.resType
          this.form.threshold = this.info.ruleExp.threshold
          this.form.ruleExp.duration = this.info.ruleExp.duration
          this.form.ruleExp.symbol = this.info.ruleExp.symbol
          this.form.ruleExp.type = this.info.ruleExp.type
          this.form.ruleExp.threshold = this.info.ruleExp.threshold
          this.form.indicatorName = this.info.resourceInfo.indicatorName
          this.form.coolTime = this.info.coolTime
          if (
            Array.isArray(this.info.resourceInfo.resInfos) &&
            this.info.resourceInfo.resInfos.length > 0
          ) {
            this.form.resInfo = this.info.resourceInfo.resInfos[0].resName
            this.resInfos = this.info.resourceInfo.resInfos
          }
        }
      },
      immediate: true
    },
    /**
     * @description: 监听 已选择的资源信息
     * @return {*}
     */
    chartWatchParam: {
      handler(newVal) {
        if (newVal.indicatorName && newVal.resInfos.length > 0) {
          // 获取图表数据
          this.getChartData()
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getClusters()
  },
  methods: {
    /**
     * @description: 设置图表
     * @param {*} xAxisData
     * @param {*} seriesDatas
     * @return {*}
     */
    setChart(xAxisData, seriesDatas, maxValue) {
      if (!this.chart) {
        this.chart = echarts.init(document.getElementById('threshold-chart')) // 初始化
      }
      let that = this
      const series = []
      seriesDatas.forEach((element, index) => {
        series.push({
          type: 'line', // 类型
          smooth: true, // 光滑
          showSymbol: false, // 显示symbol
          lineStyle: {
            // 线条样式
            width: 2, // 宽度
            color: '#5BBAF9' // 颜色
          },
          areaStyle: {
            // 区域样式
            opacity: 1,
            // 颜色渐变
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(91, 197, 249, 0.25)'
              },
              {
                offset: 1,
                color: 'rgba(255, 255, 255, 0.25)'
              }
            ])
          },
          data: element // 数据
        })
        if (index === 0&&this.form.ruleType==='智能规则') {
          // 只设置一条阈值线
          series[0]['markLine'] = {
            symbol: 'none',
            lineStyle: {
              color: '#F66173'
            },
            label: {
              position: 'insideStartTop',
              distance: [2, 5],
              color: '#F66173',
              formatter: that.form.indicatorName==='CPU使用率' ? '阈值条件>{c}%' :  that.form.indicatorName==='请求响应时间'?'阈值条件>{c}ms' : '阈值条件>{c}℃'
            },
            data: [
              {
                yAxis: this.form.threshold
              }
            ]
          }
        }else{
          series[0]['markLine'] = {
            symbol: 'none',
            lineStyle: {
              color: 'transparent'
            },
            label: {
              position: 'insideStartTop',
              distance: [2, 5],
              color: 'transparent',
            },
            data: [
              {
                yAxis: this.form.threshold
              }
            ]
          }
        }
      })
      const options = {
        title: {
          text: that.form.indicatorName,
          textStyle: {
            color: '#4A4A4A',
            fontSize: 14,
            fontWeight: 'normal'
          }
        },
        color: ['#5BBAF9'], // 颜色
        tooltip: {
          trigger: 'axis', // 触发
          backgroundColor: '#FFFFFF', // 背景色
          borderColor: '#E8E6F4', // 边框色
          borderWidth: 1, // 边框宽度
          // 自定义提示条
          formatter: (params, ticket, callback) => {
            const xAxisLable = '<div>' + params[0].data.time + '</div>'
            let content = ''
            for (const param of params) {
              content =
                content +
                '<div style="display: flex;display:-webkit-flex;justify-content:space-between;-webkit-justify-content:space-between;align-items: center;-webkit-box-align: center;">' +
                '<span>' +
                that.form.indicatorName +
                '</span><span style="margin-left: 10px;color:#0091FF;font-weight: bold;">' +
                param.data.value +
                (that.unit) +
                '</span></div>'
            }
            return (
              '<div style="box-sizing: border-box;font-size:12px;">' +
              xAxisLable +
              content +
              '</div>'
            )
          }
        },
        grid: {
          left: '5',
          right: '15',
          bottom: '10',
          top: '35',
          containLabel: true
        },
        xAxis: [
          // 横坐标
          {
            type: 'category', // 类型
            boundaryGap: false,
            axisLine: {
              // 线条样式
              show: false // 不显示
            },
            axisTick: {
              // 端点样式
              show: false // 不显示
            },
            axisLabel: {
              // 文本样式
              show: true, // 显示
              color: '#C4C6CC' // 颜色
            },
            data: xAxisData // 数据
          }
        ],
        yAxis: [
          // 纵坐标
          {
            type: 'value',
            axisLabel: {
              // 文本样式
              show: true, // 显示
              formatter: function (value) {
                var result=value+that.unit
                return result;
                },// 右侧Y轴文字显示
              color: '#C4C6CC' // 颜色
            },
            axisTick: {
              // 端点样式
              show: false // 不显示
            },
            splitLine: {
              // 分割线样式
              show: true, // 显示
              lineStyle: {
                color: '#E9E8E8', // 颜色
                type: 'dashed' // 类型
              }
            }
          }
        ],
        series: series
      }
      if (this.form.threshold > maxValue) {
        // 设置最大值以展示阈值
        options.yAxis[0].max = this.form.threshold
      }
      this.chart.setOption(options)
    },
    /**
     * @description: 获取图表数据
     * @return {*}
     */
    async getChartData() {
      try {
        let maxValue = 0
        // 初始化图表数据
        const xAxisData = []
        const seriesDatas = []
        // 请求微服务历史数据
        const res1 = await getAlarmSvcInfo({
          k8sClusterName: this.form.clusterName,
          microSvcNames: this.resInfos.map(item => {
            return item.resName
          })
        })
        if (this.form.indicatorName === 'CPU使用率' && res1.data && Array.isArray(res1.data.cpuUsage)) {
          if (res1.data.cpuUsage.length > 0 && Array.isArray(res1.data.cpuUsage[0].records)) {
            // 初始化 seriesDatas
            res1.data.cpuUsage[0].records.forEach(() => {
              seriesDatas.push([])
            })
          }
          res1.data.cpuUsage.forEach((element, index) => {
            xAxisData.push(parseTime(element.recordTimestamp, '{h}:{i}')) // 横坐标 格式化时间
            if (Array.isArray(element.records)) {
              element.records.forEach((item, recordIndex) => {
                maxValue = Math.max(maxValue, item.record)
                seriesDatas[recordIndex].push({
                  time: parseTime(element.recordTimestamp, '{y}-{m}-{d} {h}:{i}:{s}'), // 格式化时间
                  value: item.record, // 数值
                  name: item.microSvcName // 微服务名称
                })
              })
            }
          })
        } else if (this.form.indicatorName === '请求响应时间' && res1.data && Array.isArray(res1.data.reqCostTimes)) {
          if (res1.data.reqCostTimes.length > 0 && Array.isArray(res1.data.reqCostTimes[0].records)) {
            // 初始化 seriesDatas
            res1.data.reqCostTimes[0].records.forEach(() => {
              seriesDatas.push([])
            })
          }
          res1.data.reqCostTimes.forEach((element) => {
            xAxisData.push(parseTime(element.recordTimestamp, '{h}:{i}')) // 横坐标 格式化时间
            if (Array.isArray(element.records)) {
              element.records.forEach((item, recordIndex) => {
                maxValue = Math.max(maxValue, item.record)
                seriesDatas[recordIndex].push({
                  time: parseTime(element.recordTimestamp, '{y}-{m}-{d} {h}:{i}:{s}'), // 格式化时间
                  value: item.record, // 数值
                  name: item.microSvcName // 微服务名称
                })
              })
            }
          })
        } else if (this.form.indicatorName === '显卡温度' && res1.data && Array.isArray(res1.data.gpuTemps)) {
          if (res1.data.gpuTemps.length > 0 && Array.isArray(res1.data.gpuTemps[0].records)) {
            // 初始化 seriesDatas
            res1.data.gpuTemps[0].records.forEach(() => {
              seriesDatas.push([])
            })
          }
          res1.data.gpuTemps.forEach((element) => {
            xAxisData.push(parseTime(element.recordTimestamp, '{h}:{i}')) // 横坐标 格式化时间
            if (Array.isArray(element.records)) {
              element.records.forEach((item, recordIndex) => {
                maxValue = Math.max(maxValue, item.record)
                seriesDatas[recordIndex].push({
                  time: parseTime(element.recordTimestamp, '{y}-{m}-{d} {h}:{i}:{s}'), // 格式化时间
                  value: item.record, // 数值
                  name: item.microSvcName // 微服务名称
                })
              })
            }
          })
        }else if (this.form.indicatorName === '内存使用率' && res1.data && Array.isArray(res1.data.memUsageList)) {
          if (res1.data.memUsageList.length > 0 && Array.isArray(res1.data.memUsageList[0].records)) {
            // 初始化 seriesDatas
            res1.data.memUsageList[0].records.forEach(() => {
              seriesDatas.push([])
            })
          }
          res1.data.memUsageList.forEach((element) => {
            xAxisData.push(parseTime(element.recordTimestamp, '{h}:{i}')) // 横坐标 格式化时间
            if (Array.isArray(element.records)) {
              element.records.forEach((item, recordIndex) => {
                maxValue = Math.max(maxValue, item.record)
                seriesDatas[recordIndex].push({
                  time: parseTime(element.recordTimestamp, '{y}-{m}-{d} {h}:{i}:{s}'), // 格式化时间
                  value: item.record, // 数值
                  name: item.microSvcName // 微服务名称
                })
              })
            }
          })
        }else if (this.form.indicatorName === '磁盘IOPS' && res1.data && Array.isArray(res1.data.diskIopsList)) {
          if (res1.data.diskIopsList.length > 0 && Array.isArray(res1.data.diskIopsList[0].records)) {
            // 初始化 seriesDatas
            res1.data.diskIopsList[0].records.forEach(() => {
              seriesDatas.push([])
            })
          }
          res1.data.diskIopsList.forEach((element) => {
            xAxisData.push(parseTime(element.recordTimestamp, '{h}:{i}')) // 横坐标 格式化时间
            if (Array.isArray(element.records)) {
              element.records.forEach((item, recordIndex) => {
                maxValue = Math.max(maxValue, item.record)
                seriesDatas[recordIndex].push({
                  time: parseTime(element.recordTimestamp, '{y}-{m}-{d} {h}:{i}:{s}'), // 格式化时间
                  value: item.record, // 数值
                  name: item.microSvcName // 微服务名称
                })
              })
            }
          })
        }else if (this.form.indicatorName === '磁盘吞吐量' && res1.data && Array.isArray(res1.data.diskThroughputList)) {
          if (res1.data.diskThroughputList.length > 0 && Array.isArray(res1.data.diskThroughputList[0].records)) {
            // 初始化 seriesDatas
            res1.data.diskThroughputList[0].records.forEach(() => {
              seriesDatas.push([])
            })
          }
          res1.data.diskThroughputList.forEach((element) => {
            xAxisData.push(parseTime(element.recordTimestamp, '{h}:{i}')) // 横坐标 格式化时间
            if (Array.isArray(element.records)) {
              element.records.forEach((item, recordIndex) => {
                maxValue = Math.max(maxValue, item.record)
                seriesDatas[recordIndex].push({
                  time: parseTime(element.recordTimestamp, '{y}-{m}-{d} {h}:{i}:{s}'), // 格式化时间
                  value: item.record, // 数值
                  name: item.microSvcName // 微服务名称
                })
              })
            }
          })
        }else if (this.form.indicatorName === '显存使用率' && res1.data && Array.isArray(res1.data.gpuMemUsageList)) {
          if (res1.data.gpuMemUsageList.length > 0 && Array.isArray(res1.data.gpuMemUsageList[0].records)) {
            // 初始化 seriesDatas
            res1.data.gpuMemUsageList[0].records.forEach(() => {
              seriesDatas.push([])
            })
          }
          res1.data.gpuMemUsageList.forEach((element) => {
            xAxisData.push(parseTime(element.recordTimestamp, '{h}:{i}')) // 横坐标 格式化时间
            if (Array.isArray(element.records)) {
              element.records.forEach((item, recordIndex) => {
                maxValue = Math.max(maxValue, item.record)
                seriesDatas[recordIndex].push({
                  time: parseTime(element.recordTimestamp, '{y}-{m}-{d} {h}:{i}:{s}'), // 格式化时间
                  value: item.record, // 数值
                  name: item.microSvcName // 微服务名称
                })
              })
            }
          })
        }else if (this.form.indicatorName === 'GPU使用率' && res1.data && Array.isArray(res1.data.gpuUsageList)) {
          if (res1.data.gpuUsageList.length > 0 && Array.isArray(res1.data.gpuUsageList[0].records)) {
            // 初始化 seriesDatas
            res1.data.gpuUsageList[0].records.forEach(() => {
              seriesDatas.push([])
            })
          }
          res1.data.gpuUsageList.forEach((element) => {
            xAxisData.push(parseTime(element.recordTimestamp, '{h}:{i}')) // 横坐标 格式化时间
            if (Array.isArray(element.records)) {
              element.records.forEach((item, recordIndex) => {
                maxValue = Math.max(maxValue, item.record)
                seriesDatas[recordIndex].push({
                  time: parseTime(element.recordTimestamp, '{y}-{m}-{d} {h}:{i}:{s}'), // 格式化时间
                  value: item.record, // 数值
                  name: item.microSvcName // 微服务名称
                })
              })
            }
          })
        }
        if ((!this.isEdit)&&this.form.ruleType == '智能规则') {
        // 添加规则时
        // 请求智能阈值
          const res2 = await getIntelligentAlarmThreshold({
            indicatorName: this.form.indicatorName,
            svcIds: this.resInfos.map(item => {
              return item.id
            })
          })
          this.form.threshold = Number(res2.data)
        }
        this.$nextTick(() => {
          this.setChart(xAxisData, seriesDatas, maxValue)
        })
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * @description: 格式化resInfos
     * @return {*}
     */
    formatResInfos() {
      if (
        this.form.resType === '所有微服务' &&
        this.resInfoOptions.length > 0
      ) {
        this.resInfos = this.resInfoOptions.map((item) => {
          return {
            id: item.microSvcId,
            resName: item.microServiceName
          }
        })
      }
    },
    /**
     * @description: 改变告警类型 变化
     * @param {*} val
     * @return {*}
     */
    changeRuleTpye(){
      //this.$refs.addForm.clearValidate()
      this.form.clusterName = ''
      this.form.resType = ''
      this.form.resInfo = ''
      this.form.indicatorName = ''
      this.form.alarmLevel = ''
      this.form.coolTime = ''
      this.chart.clear()
    },
    /**
     * @description: 资源名称 变化
     * @param {*} val
     * @return {*}
     */
    resInfoChange(val) {
      const resInfoFind = this.resInfoOptions.find((item) => {
        return item.microServiceName === val
      })
      this.resInfos = [
        {
          id: resInfoFind.microSvcId,
          resName: resInfoFind.microServiceName
        }
      ]
      this.form.indicatorName = ''
    },
    /**
     * @description: 资源类型 变化
     * @param {*} val
     * @return {*}
     */
    resTypeChange(val) {
      if (val === '所有微服务') {
        this.form.resInfo = '' 
        this.formatResInfos()
      }
    },
    /**
     * @description: 集群切换
     * @param {*} val
     * @return {*}
     */
    clusterNameChange(val) {
      this.clusterOptions.forEach(element => {
        if(element.k8sClusterName === val){
          this.arch = element.arch
        }
      });
      this.form.resInfo = ''
      this.form.indicatorName = ''
      // 查询集群下微服务
      getAllMicroSvcName({
        clusterName: this.form.clusterName
      })
        .then((res) => {
          this.resInfoOptions = Array.isArray(res.data) ? res.data : []
          this.formatResInfos()
        })
    },
    /**
     * @description: 指标名称切换
     * @param {*} val
     * @return {*}
     */
    changeIndicatorName(val){
      if(val==='显卡温度'){
        this.unit = "℃"
      }else if(val==='磁盘IOPS'){
        this.unit = "次/S"
      }else if(val==='磁盘吞吐量'){
        this.unit = "Mbytes/S"
      }else if(val==='请求响应时间'){
        this.unit = "ms"
      }else {
        this.unit = "%"
      }
      this.form.ruleExp ={
          duration:'5',
          type:'平均值',
          symbol:'=',
          threshold:'0',
        }
    },
    /**
     * @description: 请求运行中集群
     * @return {*}
     */
    getClusters() {
      this.clusterOptionsLoading = true
      getAllClusterName({
        cloudVendor: ''
      })
        .then((res) => {
          this.clusterOptions = Array.isArray(res.data) ? res.data : []
        })
        .finally(() => {
          this.clusterOptionsLoading = false
        })
    },
    /**
     * @description: 确定
     * @return {*}
     */
    confirmClick() {
      // 校验
      this.$refs.addForm.validate((valid, obj) => {
        if (valid) {
          // 合法
          this.confirmLoading = true
          if (!this.isEdit) {
            // 添加规则
            // 请求接口
            if(this.form.ruleType==='智能规则'){
                let data = {
                ruleName: this.form.ruleName,
                duration: this.form.duration,
                alarmLevel: this.form.alarmLevel,
                coolTime:this.form.coolTime,
                intelligentParam: {
                  clusterName: this.form.clusterName,
                  resType: this.form.resType,
                  resInfos: this.resInfos,
                  indicatorName: this.form.indicatorName,
                  threshold: this.form.threshold
                }
              }
              addIntelligentRule(data)
                .then((res) => {
                  this.closeClick()
                  this.$emit('add-success')
                })
                .finally(() => {
                  this.confirmLoading = false
                })
            }else{
              let data = {
                ruleType:'普通规则',
                ruleName: this.form.ruleName,
                ruleExp: {
                  duration: this.form.ruleExp.duration,
                  type: this.form.ruleExp.type,
                  symbol: this.form.ruleExp.symbol,
                  threshold: this.form.ruleExp.threshold,
                },
                alarmLevel: this.form.alarmLevel,
                coolTime:this.form.coolTime,
                resourceInfo: {
                  clusterName: this.form.clusterName,
                  resType: this.form.resType,
                  resInfos: this.resInfos,
                  indicatorName: this.form.indicatorName,
                }
              }
              addRule(data)
                .then((res) => {
                  this.closeClick()
                  this.$emit('add-success')
                })
                .finally(() => {
                  this.confirmLoading = false
                })
            }
            
          } else {
            // 编辑
            // 请求接口
            if(this.form.ruleType==='智能规则'){
                updateIntelligentRule({
                ruleId: this.info.id,
                alarmLevel: this.form.alarmLevel,
                coolTime: this.form.coolTime,
              })
                .then((res) => {
                  this.closeClick()
                  this.$emit('edit-success')
                })
                .finally(() => {
                  this.confirmLoading = false
                })
            }else{
              updateRule({
                id: this.info.id,
                alarmLevel: this.form.alarmLevel,
                coolTime: this.form.coolTime,
                ruleExp: {
                  duration: this.form.ruleExp.duration,
                  type: this.form.ruleExp.type,
                  symbol: this.form.ruleExp.symbol,
                  threshold: this.form.ruleExp.threshold,
                },
              })
                .then((res) => {
                  this.closeClick()
                  this.$emit('edit-success')
                })
                .finally(() => {
                  this.confirmLoading = false
                })
            }
          }
        }
      })
    },
    /**
     * @description: 关闭
     * @return {*}
     */
    closeClick() {
      this.$emit('update:show', false)
    },
    /**
     * @description: 取消
     * @return {*}
     */
    cancelClick() {
      this.closeClick()
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.add-intelligent-rule-dialog {
  /deep/ .el-dialog {
    min-width: 700px;
  }
  /deep/ .el-dialog__body {
    position: relative;
    padding: 15px 25px 5px !important;
  }
  .steps {
    position: absolute;
    left: 30px;
    top: 16px;
    .order {
      width: 18px;
      height: 18px;
      line-height: 18px;
      box-sizing: border-box;
      text-align: center;
      border-radius: 50%;
      background: #d9ebff;
      border: 1px solid #0091ff;
      .textStyle(13px, 400, #0091ff);
    }
    .line {
      margin: 2px 0 2px 8px;
      height: 116px;
      border-left: 1px dashed #0091ff;
      &.line2 {
        height: 228px;
      }
      &.line3 {
        height: 222px;
      }
      &.line4 {
        height: 64px;
      }
    }
  }
  .add-form {
    margin-left: 30px;
    .el-form-item {
      margin-bottom: 18px;
    }
  }
  .title {
    .textStyle(16px, 600, #0091ff);
    line-height: 22px;
    margin-bottom: 10px;
  }
  .threshold-wrapper {
    position: relative;
    .subtitle {
      .textStyle(14px, 600, #4a4a4a);
      line-height: 22px;
      margin-bottom: 10px;
    }
    #threshold-chart {
      height: 180px;
    }
  }
  .item-hint {
    margin-top: 5px;
    display: flex;
    align-items: center;
    .icon {
      font-size: 14px;
      color: #c3c3c3;
      margin-right: 5px;
    }
    .text {
      .textStyle(14px , 400, #C3C3C3);
      line-height: 20px;
    }
  }
  /deep/ .el-radio {
    margin-right: 25px;
  }
  /deep/  .el-radio-button__orig-radio:disabled:checked+.el-radio-button__inner {
    background-color: #0091ff !important;
}
}
</style>
